package com.ssy.lingxi.common.constant.tree;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 树构造类
 * @author jw.chen
 * @version 2.0.0
 * @date 2020/7/3
 */
public class TreeUtils {

    static List<Node> allNodeList = new ArrayList<>();

    /**
     * 组装树节点
     * @param categoryIdList
     * @param categoryMap
     * @return
     */
    public static List<Node> getNodeList(Set<Long> categoryIdList, Map<String, String> categoryMap){
        return categoryIdList.stream().map(rootCategoryId -> {
            String category = categoryMap.get(String.valueOf(rootCategoryId));
            if(StringUtils.hasLength(category)){
                JSONObject jsonObject = JSONUtil.parseObj(category);
                Node node = new Node();
                node.setId(String.valueOf(rootCategoryId));
                node.setTitle(jsonObject.getStr("name"));
                node.setParentId(String.valueOf(jsonObject.getLong("parentId")));
                node.setImageUrl(jsonObject.getStr("imageUrl"));
                node.setSort(jsonObject.getInt("sort"));
                return node;
            }else{
                return null;
            }
        }).filter(Objects::nonNull).collect(Collectors.toList());
    }

    /**
     * 建立树形结构
     * @param sourceList
     * @param rootNodeList
     * @return
     */
    public static List<Node> buildTree(List<Node> sourceList, List<Node> rootNodeList){
        allNodeList = sourceList;
        List<Node> treeList =new ArrayList<>();
        for(Node node : rootNodeList) {
            buildChildTree(node);
            treeList.add(node);
        }
        return treeList.stream().sorted(Comparator.comparing(item -> item.getSort() == null ? 1 : item.getSort())).collect(Collectors.toList());
    }

    /**
     * 递归，建立子树形结构
     * @param pNode
     * @return
     */
    private static Node buildChildTree(Node pNode){
        List<Node> childrenList = new ArrayList<>();
        for(Node node : allNodeList) {
            String nodeParentId = node.getParentId();
            if(StringUtils.hasLength(nodeParentId)){
                String parentId = pNode.getId();
                if(nodeParentId.equals(parentId)){
                    childrenList.add(buildChildTree(node));
                }
            }
        }
        if(childrenList.size() > 0){
            childrenList = childrenList.stream().sorted(Comparator.comparing(item -> item.getSort() == null ? 1 : item.getSort())).collect(Collectors.toList());
            pNode.setChildren(childrenList);
        }
        return pNode;
    }

}
